package com.ydlclass.transaction;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Service
public class AccountService {

	@Autowired
	PlatformTransactionManager transactionManager;

	@Autowired
	AccountDao accountDao;

	public void transfer(Integer from,Integer to,Integer money) {
		// 在jdbc的层面事务如何开启 conn.setAutoCommit(false);
		TransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
		TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);
		try {
			// 用户1
			Account account = new Account(from,"",money);
			accountDao.update(account);

			account = new Account(to,"",-money);
			accountDao.update(account);
			// 存在大量的回调，提交、完成前后的扩展  资源的释放  挂起资源的恢复
			transactionManager.commit(transactionStatus);
		} catch (Exception e){
			transactionManager.rollback(transactionStatus);
		}
	}

}
